<?php

namespace Houdunwang\WeChat\User;

use Illuminate\Http\Client\RequestException;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\URL;
use Log;

/**
 * 获取用户资料
 */
trait Auth
{
    /**
     * 网页授权: 获取openid
     * @return mixed
     * @throws RequestException
     */
    public function snsapiBase()
    {
        return $this->request('snsapi_base');
    }

    /**
     * 网页授权: 获取用户基本信息
     * @return mixed
     * @throws RequestException
     */
    public function snsapiUserInfo()
    {
        $response = $this->request('snsapi_userinfo');
        if (isset($response['openid'])) {
            $api = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $response['access_token'] . '&openid=' . $response['openid'] . '&lang=zh_CN';
            return Http::get($api)->throw()->json();
        }
    }

    /**
     * 发送请求
     * @return mixed
     * @throws RequestException
     */
    protected function request()
    {
        $status = isset($_GET['code']) && isset($_GET['state']) && $_GET['state'] == 'STATE';
        return $status ? $this->getAccessToken($_GET['code']) : $this->getCode();
    }

    /**
     * 获取code
     * @return void
     */
    protected function getCode(string $scope = '')
    {
        $type = $this->isWeChatApp() ? 'wechat' : 'pc';
        switch ($type) {
            case 'wechat':
                $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . $this->config('appid') . '&redirect_uri=' . URL::full() .
                    '&response_type=code&scope=' . $scope . '&state=STATE#wechat_redirect';
                break;
            case 'pc':
                $url = 'https://open.weixin.qq.com/connect/qrconnect?appid=' . $this->config('appid') . '&redirect_uri=' . URL::full() .
                    '&response_type=code&scope=snsapi_login&state=STATE#wechat_redirect';
                break;
        }
        header('location:' . $url);
        die;
    }

    /**
     * 获取access_token/openid
     * @param mixed $code
     * @return mixed
     * @throws RequestException
     */
    protected function getAccessToken($code)
    {
        $api = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $this->config('appid') . '&secret=' . $this->config('secret') .
            '&code=' . $code . '&grant_type=authorization_code';
        return Http::get($api)->throw()->json();
    }
}
